package cn.edu.scau.jds.handler;

import cn.edu.scau.jds.enumeration.Season;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by junbin(seraphstorm@163.com) on 2016-01-26.
 */
@MappedTypes(value = Season.class)
@MappedJdbcTypes(value = JdbcType.VARCHAR)
public class SeasonEnumTypeHandler extends BaseTypeHandler<Season> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Season parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getName());
    }

    @Override
    public Season getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return transfer(rs.getString(columnName));
    }

    @Override
    public Season getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return transfer(rs.getString(columnIndex));
    }

    @Override
    public Season getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return transfer(cs.getString(columnIndex));
    }

    private Season transfer(String name) {
        for (Season season : Season.values()) {
            if (name.equals(season.getName()))
                return season;
        }
        throw new IllegalArgumentException("非法的枚举值！请检查是否存在名为" + name + "的Season枚举");
    }

}
